package com.woniuxy.project.campus.canteen.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.woniuxy.project.campus.AccountOpenFeign;
import com.woniuxy.project.campus.TechnicalCilnt;
import com.woniuxy.project.campus.account.model.form.AccountForm;
import com.woniuxy.project.campus.canteen.mapper.MerchantapplicationMapper;
import com.woniuxy.project.campus.canteen.mapper.ShopAdminMapper;
import com.woniuxy.project.campus.canteen.mapper.ShopsMapper;
import com.woniuxy.project.campus.canteen.model.Merchantapplication;
import com.woniuxy.project.campus.canteen.model.ShopAdmin;
import com.woniuxy.project.campus.canteen.model.Shops;
import com.woniuxy.project.campus.canteen.param.ApplyParam;
import com.woniuxy.project.campus.canteen.service.ShopAdminService;
import com.woniuxy.project.campus.canteen.util.AliyunOSS;

import com.woniuxy.project.campus.canteenModelform.AdminApproval;
import com.woniuxy.project.campus.util.Result;
import com.woniuxy.project.campus.util.StaticData;
import com.woniuxy.project.campus.util.UtilMD5;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 猫将军
 * @since 2025年02月17日
 */
@Service
public class ShopAdminServiceImpl extends ServiceImpl<ShopAdminMapper, ShopAdmin> implements ShopAdminService {

    @Resource
    private ShopAdminMapper shopAdminMapper;
    @Resource
    private ShopsMapper shopsMapper;
    @Resource
    private AliyunOSS aliyunOSS;
    @Resource
    private TechnicalCilnt technicalCilnt;
    @Resource
    private MerchantapplicationMapper merchantapplicationMapper;

    @Resource
    private AccountOpenFeign accountOpenFeign;


    //商家申请
    @Override
    public void apply(ApplyParam param) throws Exception {
        InputStream inputStream = param.getFile().getInputStream();
        byte[] bytes = new byte[1024];
        inputStream.read(bytes);
        //判断文件类型
        if (!(AliyunOSS.isJpg(bytes)||AliyunOSS.isPng(bytes))) {
            throw new IOException("文件类型不正确");
        }
        //获取文件后缀名
        String filenameExtension = StringUtils.getFilenameExtension(param.getFile().getOriginalFilename());
        //获取前缀
        String str = UUID.randomUUID().toString();
        //上传到阿里云oss
        String url = aliyunOSS.uploadFile(param.getFile().getInputStream(), str + "." + filenameExtension, "womengjiwojuan");

        //先判断手机号是否存在
        Result userInfoByMobile = accountOpenFeign.getUserInfoByMobile(param.getApplyPhone());
        AccountForm bean = BeanUtil.toBean(userInfoByMobile.getData(), AccountForm.class);
        if (bean != null) {
            throw new RuntimeException("手机号已存在");
        }
        if(bean.getName().equals(param.getApplyName())){
            throw new RuntimeException("姓名已存在");
        }
        QueryWrapper<Merchantapplication> wrapper = new QueryWrapper<>();
        wrapper.eq("shop_name", param.getShopName());
        Merchantapplication merchantapplication1 = merchantapplicationMapper.selectOne(wrapper);
        if (merchantapplication1!= null&&merchantapplication1.getAuditStatus()!= StaticData.SHOP_APPLY_STATUS_WAIT) {
            throw new RuntimeException("您已有商家申请，请耐心等待审核");
        }

        //第一 申请记录
        Merchantapplication merchantapplication = new Merchantapplication();
        merchantapplication.setShopName(param.getShopName());
        merchantapplication.setShopBossName(param.getApplyName());
        //区域
        merchantapplication.setShopAddress(param.getRegion());
        merchantapplication.setShopPhone(param.getApplyPhone());
        merchantapplication.setApplicationTime(LocalDateTime.now());
        merchantapplication.setLicense(url);
        merchantapplication.setAuditStatus(StaticData.SHOP_APPLY_STATUS_WAIT);
        merchantapplicationMapper.insert(merchantapplication);

        //查询超级管理员 id
        Result superAdminId = accountOpenFeign.getSuperAdminId();
        Object data = superAdminId.getData();
        technicalCilnt.sendCode(String.valueOf(data), "您有一条新的商家申请需要处理");

    }

    @Override
    public void adminApproval(AdminApproval bean) throws Exception {
        QueryWrapper<Merchantapplication> wrapper = new QueryWrapper<>();
        wrapper.eq("id", bean.getId());
        Merchantapplication merchantapplication = merchantapplicationMapper.selectOne(wrapper);
        Result userInfoByMobile = accountOpenFeign.getUserInfoByMobile(merchantapplication.getShopPhone());
        AccountForm bean1 = BeanUtil.toBean(userInfoByMobile.getData(), AccountForm.class);
        if (merchantapplication == null) {
            throw new RuntimeException("暂无申请记录");
        }
        System.out.println("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&"+bean.getStatus());
        System.out.println(bean.getRemark());
        System.out.println(bean.getId());
        if (bean.getStatus() == StaticData.ADMIN_APPLY_STATUS_PASS&&""==bean.getRemark()) {
            //通过审核
            System.out.println("通过审核");
            merchantapplication.setAuditStatus(StaticData.SHOP_APPLY_STATUS_PASS);
            merchantapplication.setReviewerTime(LocalDateTime.now());
            merchantapplication.setAuditStatus(StaticData.SHOP_APPLY_STATUS_PASS);
            merchantapplicationMapper.updateById(merchantapplication);
            //更改权限
            bean1.setRoleId(StaticData.SHOP_ROLE_ID);
            bean1.setRoleName(StaticData.SHOP_ROLE_NAME);
            AccountForm bean2 = BeanUtil.toBean(bean1, AccountForm.class);
            accountOpenFeign.updateUserInfo(bean2);
            //改角色表权限
            accountOpenFeign.updateRoleId(bean1.getId());
            //创建老板账户
            ShopAdmin shopAdmin = new ShopAdmin();
            shopAdmin.setShopAddress(merchantapplication.getShopAddress());
            shopAdmin.setAccountId(bean1.getId());
            shopAdmin.setShopName(merchantapplication.getShopName());
            shopAdmin.setShopBossName(merchantapplication.getShopBossName());
            shopAdmin.setShopPhone(merchantapplication.getShopPhone());
            shopAdminMapper.insert(shopAdmin);
            //创建商家
            AccountForm accountForm = new AccountForm();
            accountForm.setName(merchantapplication.getShopBossName());
            accountForm.setPhone(merchantapplication.getShopPhone());
            String s = UtilMD5.md5("123456", merchantapplication.getShopPhone());
            accountForm.setPassword(s);
            accountForm.setReName(StaticData.SHOP_ROLE_NAME);
            accountForm.setRoleId(StaticData.SHOP_ROLE_ID);
            accountOpenFeign.addMerchant(accountForm);
            //创建商铺 基本信息
            Shops shops = new Shops();
            shops.setShopName(merchantapplication.getShopName());
            shops.setAddress(merchantapplication.getShopAddress());
            shops.setShopAccountId(bean1.getId());
            shops.setAccountId(String.valueOf(bean1.getId()));
            shops.setBossName(merchantapplication.getShopBossName());
            shops.setPhoneNum(merchantapplication.getShopPhone());
            shops.setAddress(merchantapplication.getShopAddress());
            shops.setBusinessStatus(StaticData.SHOP_STATUS_OPEN);
            shops.setAccountName(merchantapplication.getShopBossName());
            shops.setAccountId(String.valueOf(bean1.getId()));
            shops.setLicense(merchantapplication.getLicense());
            shops.setCarTime(LocalDateTime.now());
            shopsMapper.insert(shops);
            //发送通知
            technicalCilnt.sendCode(String.valueOf(bean1.getId()), "恭喜您，您的申请的商户入驻已通过审核，请重新登陆了解更多信息");
        }else if (""!=bean.getRemark()&&bean.getStatus()==StaticData.ADMIN_APPLY_STATUS_NOT_PASS) {
            System.out.println("不通过审核");
            merchantapplication.setReviewerTime(LocalDateTime.now());
            merchantapplication.setAuditStatus(StaticData.SHOP_APPLY_STATUS_NOT_PASS);
            merchantapplication.setRemarks(bean.getRemark());
            merchantapplicationMapper.updateById(merchantapplication);
            //发送通知
            technicalCilnt.sendCode(String.valueOf(bean1.getId()), "您的申请的商户入驻未通过审核，请重新提交申请");
        }
    }
}
